package org.javaboy.attempts_login_demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginAttemptService {

    @Autowired
    StringRedisTemplate redisTemplate;

    public static final Integer MAX_ATTEMPTS = 10;

    public static final String ATTEMPTS_LOGIN_PREFIX = "login_attempts:";

    /**
     * 每当用户输错密码的时候，就调用这个方法，向 Redis 保存数据
     *
     * @param username
     */
    public void loginFailed(String username) {
        redisTemplate.opsForValue().increment(ATTEMPTS_LOGIN_PREFIX + username);
        redisTemplate.expire(ATTEMPTS_LOGIN_PREFIX + username, 1, TimeUnit.DAYS);
    }

    /**
     * 超过最大重试次数，账户被锁定
     *
     * @param username
     * @return
     */
    public boolean isLoginLocked(String username) {
        String attempts = redisTemplate.opsForValue().get(ATTEMPTS_LOGIN_PREFIX + username);
        return attempts != null && Long.parseLong(attempts) >= MAX_ATTEMPTS;
    }

    /**
     * 登录成功，则之前登录失败的记录清零
     *
     * @param username
     */
    public void clearLoginAttempts(String username) {
        redisTemplate.delete(ATTEMPTS_LOGIN_PREFIX + username);
    }
}
